#include "CFramelessWidget.h"
#include <qt_windows.h>
#include <windows.h>
#include <windowsx.h>
#include <QVBoxLayout>
#include <QMouseEvent>
CFramelessWidget::CFramelessWidget(QWidget *parent) : QWidget(parent)
{
    this->setWindowFlags(Qt::FramelessWindowHint |
Qt::WindowMinMaxButtonsHint);
    setAttribute(Qt::WA_Hover);
    this->setStyleSheet("background-color: rgb(70, 70, 70);");
}
CFramelessWidget::~CFramelessWidget()
{}
//该函数实现了窗口的拖拽拉伸
bool CFramelessWidget::nativeEvent(const QByteArray& eventType, void*
message, long* result)
{
   MSG* param = static_cast<MSG*>(message);
   switch (param->message)
   {
   case WM_NCHITTEST:
   {
       int nX = GET_X_LPARAM(param->lParam) - this->geometry().x();
       int nY = GET_Y_LPARAM(param->lParam) - this->geometry().y();
       if (nX > m_nBorderWidth && nX < this->width() - m_nBorderWidth &&
           nY > m_nBorderWidth && nY < this->height() - m_nBorderWidth)
       {
           if (childAt(nX, nY) != nullptr)
               return QWidget::nativeEvent(eventType, message, result);
       }
       if ((nX > 0) && (nX < m_nBorderWidth))
           *result = HTLEFT;
       if ((nX > this->width() - m_nBorderWidth) && (nX < this->width()))
           *result = HTRIGHT;
       if ((nY > 0) && (nY < m_nBorderWidth))
           *result = HTTOP;
       if ((nY > this->height() - m_nBorderWidth) && (nY < this->height()))
           *result = HTBOTTOM;
       if ((nX > 0) && (nX < m_nBorderWidth) && (nY > 0)
           && (nY < m_nBorderWidth))
           *result = HTTOPLEFT;
       if ((nX > this->width() - m_nBorderWidth) && (nX < this->width())
           && (nY > 0) && (nY < m_nBorderWidth))
           *result = HTTOPRIGHT;
       if ((nX > 0) && (nX < m_nBorderWidth)
           && (nY > this->height() - m_nBorderWidth) && (nY<this->height()))
           *result = HTBOTTOMLEFT;
       if ((nX > this->width() - m_nBorderWidth) && (nX < this->width())
           && (nY > this->height() - m_nBorderWidth) && (nY<this->height()))
           *result = HTBOTTOMRIGHT;
              return true;
          }//end of case
          }//end of switch
          return false;
}
// 鼠标按下时记录初始位置
void CFramelessWidget::mousePressEvent(QMouseEvent *event)
{
    // 只响应左键拖拽（通常在标题栏区域拖拽，这里简化为整个窗口可拖）
    if (event->button() == Qt::LeftButton) {
        _isDragging = true;
        // 记录鼠标相对于窗口左上角的位置
        _dragStartPos = event->pos();
    }
    // 传递事件给父类（避免影响其他控件）
    QWidget::mousePressEvent(event);
}

// 鼠标移动时计算窗口新位置
void CFramelessWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (_isDragging) {
        // 计算窗口新位置：当前鼠标全局位置 - 初始相对位置
        QPoint newPos = event->globalPos() - _dragStartPos;
        move(newPos);  // 移动窗口
    }
    QWidget::mouseMoveEvent(event);
}

// 鼠标释放时结束拖拽
void CFramelessWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        _isDragging = false;
    }
    QWidget::mouseReleaseEvent(event);
}
